package com.mojo.concurrent.concurrent_01_thread;

import java.util.concurrent.*;

/**
 * future使用示例
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/4/27 18:10
 */
public class FutureTaskDemo {
    public static void main(String[] args) {
        //构造
        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 1);
        //run方法
        //futureTask.run();
        //executorService+futureTask
        // futureTaskWithExecutorService();
        //thread+futureTask
        //futureTaskWithThread();
    }
    private static void futureTaskWithExecutorService() {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        Future<?> future = executorService.submit(new FutureTask<>(() ->
        {
            System.out.println(">>>线程池提交");
            return "Future callable";
        }));
        String get = null;
        if (!future.isDone()) {
            System.out.println(">>>Future暂未完成");
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            get = (String) future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(">>" + get);
        executorService.shutdown();
    }

    private static void futureTaskWithThread() {
        FutureTask<String> task1 = new FutureTask<>(() -> {
            Thread.sleep(2000L);
            int i = 10 / 0;
            return "callable";
        });
        new Thread(task1).start();
        String s = null;
        if (!task1.isDone()) {
            System.out.println(">>>>>>>>futureTask暂未完成");
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(">>>>" + s);
        try {
            s = task1.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(">>>>" + s);
    }
}
